/**
 * 下午6:58:00
 */
package com.hsnn.medstgmini.pro.project.dao.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.pro.project.dao.BidPubSettingsDao;
import com.hsnn.medstgmini.pro.project.model.form.ProdProjectForm;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @author hsnn
 *
 */
@Repository
public class BidPubSettingsDaoImpl implements BidPubSettingsDao {

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	private Session getSession() {
		Session session = sessionFactory.getCurrentSession();
		if (null == session) {
			session = sessionFactory.openSession();
		}
		return session;
	}
	
	@Override
	public Pagination getBidPubSettingsList(Pagination page) {
		StringBuffer sql = new StringBuffer()
		.append(" select bps.bid_pub_settings_id bidPubSettingsId, ")
		.append(" bps.script_name scriptName, ")
		.append(" su1.name scriptSubmitUser, ")
		.append(" bps.script_submit_datetime scriptSubmitDatetime, ")
		.append(" su2.name execUser, ")
		.append(" bps.exec_datetime execDatetime, ")
		.append(" bps.status ")
		.append(" from bid_pub_settings bps left join sys_user su1 on su1.id = bps.script_submit_user ")
		.append(" left join sys_user su2 on su2.id = bps.exec_user ")
		.append(" where bps.proj_id = :projId order by bps.script_submit_datetime desc");
		Query query= getSession().createSQLQuery(sql.toString());
		query.setParameter("projId", page.getConditions().get("projId"));
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}

	/**
	 * @category sql脚本查询
	 * @author 应晓川
	 * @date  2015年9月2日11:36:17
	 * @param  @return
	 */
	@Override
	public Pagination getExecScriptFile(Pagination page) {
	
		Query queryList =  getSession().createSQLQuery(page.getConditions().get("sql"));
		page.setRows(queryList.list());
		//查列头
		Query query =  getSession().createSQLQuery(page.getConditions().get("sql"));
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		query.setFirstResult(0).setMaxResults(1);
		List<String> titleList  = new ArrayList<String>();
		@SuppressWarnings("unchecked")
		HashMap<String,String> map = (HashMap<String, String>) query.uniqueResult();
		for(Entry<String, String> m :map.entrySet()){
			titleList.add(m.getKey());
		} 
		Collections.reverse(titleList);//倒序排列
		page.setForm(titleList);		
		return page;
	}

	/**
	 * @category 根据key-value确定一条数据
	 * @author 应晓川
	 * @param entity 要查询的实体对象
	 * @param key 对象中某一字段
	 * @param value 对象中某一字段的值
	 * @return
	 */
	@Override
	public Object getUniquerResult(Class<?> entity, String key, String value) {
		Criteria criteria = getSession().createCriteria(entity);
		criteria.add(Restrictions.eq(key, value));
		return criteria.uniqueResult();
		
	}


	@Override
	public Pagination getExecScriptFileHashmapList(Pagination page) {
		Query queryList =  getSession().createSQLQuery(page.getConditions().get("sql"));
		queryList.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(queryList.list());
		return page;
	}

	/**
	 *@category 获取公示结果列表
	 *@author 应晓川
	 *@date 2015年9月1日19:26:23
	 *@return
	 */
	@Override
	public Pagination getBidPubSettingsResultList(Pagination page) {
		StringBuffer sql = new StringBuffer()
		.append(" select bps.bid_pub_settings_id bidPubSettingsId, ")
		.append(" bps.script_name scriptName, ")
		.append(" su1.name scriptSubmitUser, ")
		.append(" bps.script_submit_datetime scriptSubmitDatetime, ")
		.append(" su2.name execUser, ")
		.append(" bps.exec_datetime execDatetime ")
		.append(" from bid_pub_settings bps left join sys_user su1 on su1.id = bps.script_submit_user ")
		.append(" left join sys_user su2 on su2.id = bps.exec_user ")
		.append(" where bps.proj_id = :projId and bps.status=1 order by bps.script_submit_datetime desc");
		Query query= getSession().createSQLQuery(sql.toString());
		query.setParameter("projId", page.getConditions().get("projId"));
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}

	/**
	 * @category 公示查看 （已执行状态）
	 * @author 应晓川
	 * @date  2015年9月7日17:18:12
	 * @param 
	 */
	@Override
	public Pagination getBidPubSettingsResultListCheck(Pagination page) {
		ProdProjectForm form = (ProdProjectForm) page.getForm();
		StringBuffer sql = new StringBuffer()
		.append(" select bps.bid_pub_settings_id bidPubSettingsId, ")
		.append(" bps.script_name scriptName, ")
		.append(" bp.create_datetime createDatetime, ")
		.append(" bp.name , ")
		.append(" su2.name execUser, ")
		.append(" bps.exec_datetime execDatetime ")
		.append(" from bid_pub_settings bps left join bid_project bp on bp.proj_id = bps.proj_id ")
		.append(" left join sys_user su2 on su2.id = bps.exec_user ")
		.append(" where bps.status = 1 ");
		if (form != null) {
			String projId = form.getProjId();
			if(StringUtils.isNotBlank(projId)){
				sql.append(" AND bp.proj_id = :projId  ");
			}
		}
		sql.append(" order by bp.create_datetime desc ");
		Query query= getSession().createSQLQuery(sql.toString());
		if (form != null) {
			String projId = form.getProjId();
			if(StringUtils.isNotBlank(projId)){
				query.setParameter("projId", projId);
			}
		}
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}


	@Override
	public List<Object> getProjNameList() {
		String sql = "select bp.proj_id projId,bp.name FROM bid_project bp ";
		Query query=  getSession().createSQLQuery(sql);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	}

}
